package easy.相交链表;


public class Solution2 {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) {
            return null;
        }
        ListNode pA = headA, pB = headB;
        //我走过你走过的路，只为和你相逢
        while (pA != pB) {
            pA = pA == null ? headB : pA.next;
            pB = pB == null ? headA : pB.next;
        }
        return pA;
    }

    public static void main(String[] args) {
        // 创建节点
        ListNode n1 = new ListNode(4);
        ListNode n2 = new ListNode(1);
        ListNode n3 = new ListNode(5);
        ListNode n4 = new ListNode(6);
        ListNode n5 = new ListNode(1);
        ListNode n6 = new ListNode(8);
        ListNode n7 = new ListNode(4);
        ListNode n8 = new ListNode(5);
        // 连接节点
        n1.next = n2;
        n2.next = n6;
        n3.next = n4;
        n4.next = n5;
        n5.next = n6;
        n6.next = n7;
        n7.next = n8;
        // head 指向第一个节点
        ListNode head = n1;
        ListNode head2 = n3;
        Solution2 solution = new Solution2();
        System.out.println(solution.getIntersectionNode(head, head2));
    }
}
